<template>
  <div>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="客户池" name="customer">
        <custom-container ref="customContainerRef" :config="mainConfig"></custom-container>
        <setForm
          ref="setFormRef"
          :user-info-list="userInfo.deptId"
          @changeList="handleQuery"
          @handleFollowDetail="handleFollowDetail"
        />
        <upload ref="uploadForm" />
        <saleForm ref="setsaleFormRef" />
      </el-tab-pane>
      <el-tab-pane label="销售池" name="sale">
        <custom-container
          v-if="saleVisible"
          ref="customSaleContainerRef"
          :config="saleConfig"
          :user-info-list="userInfo.deptId"
        ></custom-container>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script lang="ts" setup>
import { computed, ref, getCurrentInstance, reactive, defineAsyncComponent, provide } from 'vue'
import { ElButton, ElMessageBox, ElMessage, ElSwitch } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
import { Plus, Edit, Delete, Search, Upload, Bottom, Key, UploadFilled } from '@element-plus/icons-vue'
import { pxToRem } from '@/utils'
import userDicts, { DictDirection } from '@/store/modules/dicts'
import userStore from '@/store/modules/user'
import {
  getCustomerData,
  setCustomerAdd,
  setCustomerDel,
  setCustomerUpdate,
  setCustomerFollow,
  getFollowPool,
  setStatus,
  getFollowDetail,
  addFollowDetail,
  editFollowDetail,
  delFollowDetail,
  listUserTab,
  setDistribute,
} from '@/api/customerAnalysis'

const setForm = defineAsyncComponent(() => import('./components/setForm.vue'))
const saleForm = defineAsyncComponent(() => import('./components/saleForm.vue'))
const upload = defineAsyncComponent(() => import('./components/upload.vue'))
const store = userStore()
const userInfo = computed(() => store.user)
// 当前页面
const dicts = userDicts()
dicts.setDicts(DictDirection.客户类型)
dicts.setDicts(DictDirection.跟进人)

const handleClick = (tab: TabsPaneContext, event: Event) => {
  if (tab.props.name == 'sale') {
    querySaleParams.value.status = 1
    saleVisible.value = true
  }
}
let // 选中行的ID
  ids = []
const activeName = ref('customer'),
  // 销售池
  saleContainerRef = ref(''),
  // 是否在销售池
  saleVisible = ref(false),
  openFollowDetail = ref(false),
  followDetail = ref([]),
  openFollowDetailForm = ref(false),
  // 销售池主表ID
  saleMid = ref(undefined),
  // 跟进详情新增表单
  followDetailForm = ref(null),
  followDetailFormTitle = ref(''),
  followDetailWritten = ref(false),
  maxHeight = ref(0),
  // 多选
  multiple = ref(true),
  customContainerRef = ref(null),
  // 新增表单状态
  openDetail = ref(false),
  // 新增\修改表单标题
  detailTitle = ref(null),
  // 新增\修改表单
  detailForm = ref({
    customerSimpleName: undefined,
    customerFullName: undefined,
    type: undefined,
    contacts: undefined,
    telephone: undefined,
    address: undefined,
  }),
  // 导入
  uploadForm = ref(null)

// 查询客户池
const handleQuery = () => {
  queryParams.value.pageNum = 1
  customContainerRef.value.getList()
}
// 客户池
const setFormRef = ref(null),
  // 销售池
  customSaleContainerRef = ref(null),
  // 跟进池详情
  setsaleFormRef = ref(null),
  {
    appContext: {
      config: {
        globalProperties: { $download, $download2 },
      },
    },
  } = getCurrentInstance()
// 查询条件
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  customerSimpleName: undefined,
  customerFullName: undefined,
  followUpPerson: undefined,
  type: undefined,
  status: undefined,
})
// 销售池
const querySaleParams = ref({
  pageNum: 1,
  pageSize: 10,
  customerSimpleName: undefined,
  customerFullName: undefined,
  followUpPerson: undefined,
  status: undefined,
})
// 非多个禁用
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  console.log(rows)
  ids = rows.map((item) => item.id)
  multiple.value = !rows.length
}
// 新增
const handleAdd = () => {
  setFormRef.value.openDetail = true
  setFormRef.value.detailTitle = '新增'
}
// 修改
const handleUpdate = (row: { [key: string]: any }) => {
  setFormRef.value.openDetail = true
  setFormRef.value.detailTitle = '修改'
  const rows = JSON.parse(JSON.stringify(row))
  rows.type = rows.type == 0 ? '直客' : rows.type == 1 ? '同行' : ''
  console.log(rows.type)
  // setFormRef.value.detailForm = rows;
  // console.log(setFormRef.value.detailForm);
  // const id = rows?.id || ids;
  // console.log(id);
  setFormRef.value.detailForm = rows
  // setFormRef.value.getList(id);
}
// 删除
let customerId = []
const handleDelete = (row: { [key: string]: any }) => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  customerId = (row && row.id) || ids
  ElMessageBox.confirm(`是否确认删除用户编号为"${ customerId }"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => setCustomerDel(customerId))
  .then((res) => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error('删除失败')
    }
  })
  .catch((error) => {
    if ((error == 'cancel')) {
      ElMessage.info('取消删除')
    }
  })
}
// 表格格式化
const formatterRules = (row, column) => {
  if (column.property == 'status') {
    return row[column.property] == 0 ? '初始状态' : row[column.property] == 1 ? '跟进状态' : row[column.property] == 2 ? '放弃跟进' : row[column.property] == 3 ? '开发完成' : ''
  } if (column.property == 'type') {
    return row[column.property] == 0 ? '直客' : row[column.property] == 1 ? '同行' : ''
  }
  return row[column.property]
}
// 批量分配跟进人
const handleDistribute = (row: { [key: string]: any }) => {
  setFormRef.value.openDistribute = true
  if (row.id) {
    setFormRef.value.distributeForm.id = row.id
  } else {
    setFormRef.value.distributeForm.ids = ids
  }
}
// 客户池导入
const handleImport = () => {
  uploadForm.value.open = true
}
// 导出
const handleExport = () => {
  $download('/system/customer/pool/export_cust_poll', {}, `客户池_${ new Date().getTime() }.xlsx`)
}
// 客户池跟进
const handleFollow = (row: { [key: string]: any }) => {
  const data = { id: row.id, followUpPerson: row.followUpPerson || userInfo.value.userName, deptId: userInfo.value.deptId, status: 1 }
  ElMessageBox.confirm('是否跟进此客户？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => setCustomerFollow(data))
  .then((res) => {
    if (res.code === 200) {
      ElMessage.success('操作成功')
      setFormRef.value.openDistribute = false
      handleQuery()
    }
  })
  .catch((err = 'cancel') => {
    ElMessage.info('取消操作')
  })
}
// 客户池跟进详情
const handleFollowDetail = (row: { [key: string]: any }) => {
  setsaleFormRef.value.openFollowDetail = true
  // const customerPoolId = row.customerPoolId || row.id;
  // const followUpPerson = row.followUpPerson;
  // customSaleContainerRef.value.followDetailForm.value.customerPoolId = customerPoolId;
  // customSaleContainerRef.value.followDetailForm.followUpPerson = followUpPerson;
  // customSaleContainerRef.value.followDetailWritten = row.status == 2 || row.status == 3;
  // getFollowDetail(customerPoolId).then((res) => {
  // 	if (res.code == 200) {
  // 		customSaleContainerRef.value.followDetail = res.rows;
  // 		customSaleContainerRef.value.openFollowDetail = true;
  // 	}
  // });
}
// 放弃跟进按钮
const handleAbandonFollow = (row: { [key: string]: any }) => {
  if (row.status == 3) return ElMessage.error('开发已完成，不可操作')
  const { id, followUpPerson, followUpTime } = JSON.parse(JSON.stringify(row))
  const data = { id, followUpPerson, followUpTime, status: undefined }
  data.status = 2
  ElMessageBox.confirm('是否放弃跟踪此客户', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => setStatus(data))
  .then((res) => {
    if (res.code == 200) {
      ElMessage.success('已放弃跟踪')
      customSaleContainerRef.value.getList()
    }
  })
  .catch((error) => {
    if ((error == 'cancel')) {
      ElMessage.info('取消删除')
    }
  })
}
// 完成开发按钮
const handleFinish = (row: { [key: string]: any }) => {
  if (row.status == 3) return ElMessage.error('开发已完成，不可操作')
  const { id, followUpPerson, followUpTime } = JSON.parse(JSON.stringify(row))
  const data = { id, followUpPerson, followUpTime, status: undefined }
  data.status = 3
  ElMessageBox.confirm('确认开发完成', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => setStatus(data))
  .then((res) => {
    if (res.code == 200) {
      ElMessage.success('开发已完成')
      customSaleContainerRef.value.getList()
    }
  })
  .catch((error) => {
    if ((error == 'cancel')) {
      ElMessage.info('取消删除')
    }
  })
}
// 销售池导出
const handleSaleExport = () => {
  $download2('/system/customer/pool/export_follow', {}, `销售池_${ new Date().getTime() }.xlsx`)
}

const mainConfig = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '客户简称',
            prop: 'customerSimpleName',
            minWidth: '240',
            option: {
              placeholder: '请输入客户简称',
              clearable: true,
              size: 'middle',
            },
          },
          {
            label: '客户全称',
            prop: 'customerFullName',
            minWidth: '240',
            option: {
              placeholder: '请输入客户全称',
              clearable: true,
              size: 'middle',
            },
          },
          {
            label: '类型',
            prop: 'type',
            type: 'select',
            option: {
              placeholder: '请选择类型',
              dictInfo: {
                dict: DictDirection.客户类型,
              },
              size: 'middle',
            },
          },
        ],
        queryParams: queryParams.value,
      },
      btns: [
        {
          title: '新增',
          onclick: handleAdd,
          icon: Plus,
        },
        {
          title: '删除',
          onClick: handleDelete,
          type: 'danger',
          disabled: multiple.value,
          icon: Delete,
        },
        {
          title: '分配',
          clickFun: handleDistribute,
          type: 'danger',
          disabled: multiple.value,
          icon: Plus,
          // directive: [['hasPermi', ['system:pool:follow']]],
        },
        {
          title: '导入',
          onclick: handleImport,
          type: 'info',
          icon: Upload,
        },
        {
          title: '导出',
          onclick: handleExport,
          type: 'warning',
          icon: Bottom,
        },
      ],
      table: {
        columns: [
          {
            type: 'selection',
            width: '55',
            align: 'center',
          },
          { label: '客户简称', prop: 'customerSimpleName', showOverflowTooltip: true, minWidth: '25', align: 'center' },
          { label: '客户全称', prop: 'customerFullName', showOverflowTooltip: true, minWidth: '25', align: 'center' },
          {
            label: '创建时间',
            prop: 'createDate',
            minWidth: '20',
            align: 'center',
          },
          {
            label: '类型',
            prop: 'type',
            minWidth: '20',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.客户类型,
              rowKey: 'type',
            },
          },
          { label: '联系人 ', prop: 'contacts', minWidth: '25', align: 'center' },
          { label: '电话 ', prop: 'telephone', minWidth: '25', align: 'center' },
          { label: '地址', prop: 'address', minWidth: '25', align: 'center' },
          {
            label: '操作',
            // visible: !saleVisible.value,
            // flag: 'customerButton',
            fixed: 'right',
            minWidth: '100',
            align: 'center',
            showOverflowTooltip: false,
            render: (h, params) => {
              const buttons = [
                {
                  title: '修改',
                  clickFun: handleUpdate,
                },
                {
                  title: '跟进',
                  clickFun: handleFollow,
                },
                {
                  title: '分配',
                  clickFun: handleDistribute,
                  directive: [['hasPermi', ['system:pool:follow']]],
                },
                {
                  title: '跟进详情',
                  clickFun: handleFollowDetail,
                },
                {
                  title: '删除',
                  clickFun: handleDelete,
                },
              ]
              return buttons.map((el) => h(
                ElButton,
                {
                  text: true,
                  type: 'primary',

                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              ))
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: getCustomerData,
    }
  },
  set(val) {
    return val
  },
})
           
</script>
